#include <iostream>
#include <unistd.h>
#include <string>
#include <cstring>
#include <errno.h>

int main()
{
    std::string methon = getenv("METHOD");
    std::string paramenter;

    int post_length = 0;

    if (methon == "GET")
    {
        paramenter = getenv("PARAMENTER");
    }else if (methon == "POST")
    {
        //1.获取先出发来CGI的参数信息
        post_length = atoi(getenv("CONTENT-LENHTH"));
        // std::cerr << "post-length:" << post_length << std::endl;
        while (post_length > 0)
        {
            char x = 'g';
            int bx =  read(0, &x, 1);
            if (bx == -1)
                std::cerr << strerror(errno) << std::endl;

            paramenter.push_back(x);
            post_length--;
        }
    }

    
    //2.解析正文，并给予运算。这里只用输出一个数来表示CGI结果
    std::cout << "<html>"; 
    std::cout << "<body>";
    std::cout << "<meta charset=\"UTF-8\">";
    std::cout << "<h1>" << paramenter << "</h1>";
    std::cout << "<body>";
    std::cout << "<html>" << std::endl;

    //马上退出，有没有都差不多
    if (methon == "POST")
    {
        close(1);
        close(0);
    }
    exit(0);
}


